import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/expert/zq_hot_expert_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/server/api/expert_api.dart';
import 'package:sports_new/server/api/user_api.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/check_widget.dart';
import 'package:sports_new/widgets/circular.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import 'package:sports_new/widgets/base/qkd_text.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';

enum SuggestExpertForm{
  bottomSheet,
  list,
  grid
}

class SuggestExpertWidget extends StatefulWidget {
  const SuggestExpertWidget.sheet({super.key, required this.sportsId, this.tapFocus}):form = SuggestExpertForm.bottomSheet,noData = null;
  const SuggestExpertWidget.list({super.key, required this.sportsId}):form = SuggestExpertForm.list,tapFocus = null,noData = null;
  const SuggestExpertWidget.grid({super.key, required this.sportsId, this.tapFocus, this.noData}):form = SuggestExpertForm.grid;

  final SuggestExpertForm form;
  final int sportsId;
  final Widget? noData;
  final Function()? tapFocus;

  @override
  State<SuggestExpertWidget> createState() => _SuggestExpertWidgetState();
}

class _SuggestExpertWidgetState extends State<SuggestExpertWidget> {
  List<HotExpertEntity> allList = [];
  List<List<HotExpertEntity>>? expertList;
  List<List<String>> focusList = [];
  int _index = 0;
  int _indexMax = 0;

  int get index => _index;
  set index(int value) => setState(() {
    _index = value;
    if(index > _indexMax){
      index = 0;
    }
  });

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async{
    allList = await ExpertApi.getSuggestExpert("", widget.form == SuggestExpertForm.list?1:index+1, widget.sportsId);
    if(allList.length >= 18) allList = allList.sublist(0,18);
    int length = allList.length;
    expertList = [];
    while(length >= 6){
      expertList!.add(allList.sublist(_indexMax*6,_indexMax*6+6));
      length -= 6;
      if(length >= 6) _indexMax++;
    }
    if(expertList.noValue && widget.form == SuggestExpertForm.bottomSheet) navigator?.pop();
    for (var element in expertList!) {
      focusList.add(element.map((e) => e.expertId??"").toList());
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return LoadingWidget<bool>(
      isLoading: expertList == null,
      loading: Container(),
      data: false,
      child: () {
        switch(widget.form){
          case SuggestExpertForm.bottomSheet:
            return expertList.noValue?Container():sheet();
          case SuggestExpertForm.list:
            return expertList.noValue?Container(height: 20):list();
          case SuggestExpertForm.grid:
            return expertList?.length == 0?(widget.noData??Container()):grid();
        }
      }
    );
  }

  Widget sheet(){
    return BottomSheet(
      onClosing: (){},
      backgroundColor: Colours.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(12))
      ),
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedOverflowBox(
            alignment: Alignment.topCenter,
            size: Size(Get.width, 0),
            child: ClipRRect(
              borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
              child: Image.asset(Utils.getImgPath('suggest_expert_bg.png'),width: Get.width,fit: BoxFit.cover),
            ),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(width: 4),
              Row(
                children: [
                  SizedOverflowBox(
                    size: const Size(80, 76),
                    alignment: Alignment.bottomCenter,
                    child: Image.asset(Utils.getImgPath("suggest_expert_icon.png"),width: 80)
                  ),
                  head()
                ],
              ),
              const Spacer(),
              GestureDetector(
                onTap: navigator?.pop,
                child: Padding(
                  padding: const EdgeInsets.only(top: 16,right: 16),
                  child: Image.asset(
                    Utils.getImgPath("bottomsheet_close.png"),
                    width: 24
                  ),
                ),
              )
            ],
          ),
          gridView().paddingAll(16),
          Padding(
           padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
            child: buttonArea()
          )
        ],
      )
    );
  }

  Widget list(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 12, 16, 6),
          child: head()
        ),
        MediaQuery.removePadding(
          context: context,
          removeTop: true,
          child: SizedBox(
            height: 139,
            child: ScrollConfiguration(
              behavior: const ScrollBehavior().copyWith(overscroll: false),
              child: ListView(
                shrinkWrap: true,
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                children: allList.map(
                  (e) => item(e)
                ).toList().insertEvery(Container(width: 8)) ?? []
              ),
            ),
          ),
        ),
        Container(height: 12)
      ],
    );
  }

  Widget grid(){
    return Circular(
      color: Colours.white,
      radius: 8,
      margin: const EdgeInsets.symmetric(horizontal: 8),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          head().paddingSymmetric(vertical: 12),
          gridView(),
          buttonArea().paddingSymmetric(vertical: 16),
        ],
      ),
    );
  }

  Widget gridView(){
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        crossAxisCount: 3,
        childAspectRatio: 106/(widget.form==SuggestExpertForm.bottomSheet?128:130),
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        children: expertList?[index].map(
          (e) => item(e)
        ).toList() ?? []
      ),
    );
  }

  Widget item(HotExpertEntity? entity){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        if(widget.form == SuggestExpertForm.list){
          Get.toNamed(Routes.userPage,arguments: entity?.expertId,parameters: {"type":"2"});
        }else{
          if(!focusList[index].contains(entity?.expertId)){
            focusList[index].add(entity!.expertId!);
          }else {
            focusList[index].remove(entity!.expertId!);
          }
          setState(() {});
        }
      },
      child: Circular(
        color: Colours.greyF7F9FC,
        width: 106,
        radius: 8,
        child: Stack(
          alignment: Alignment.topRight,
          children: [
            Positioned.fill(
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 12),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Column(
                      children: [
                        QkdImage(
                            imageUrl: entity?.logo,
                            width: 52, height: 52,
                            shape: BoxShape.circle
                        ).paddingOnly(bottom: 4),
                        QkdText(
                            entity?.name,
                            fontSize: 12,
                            fontWeight: FontWeight.w500
                        ).paddingOnly(bottom: 4)
                      ],
                    ),
                    if(widget.form == SuggestExpertForm.list)
                    QkdText(
                      entity?.value,
                      needCenter: true,
                      color: Colours.grey99,
                      fontSize: 11
                    )
                    else
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Circular(
                          color: Colours.main1,
                          radius: 10.5,
                          height: 21,
                          alignment: Alignment.center,
                          padding: const EdgeInsets.symmetric(horizontal: 12),
                          child: QkdText(
                            entity?.value,
                            needCenter: true,
                            color: Colours.main,
                            fontSize: 11
                          )
                        ),
                      ],
                    ),
                    if(widget.form == SuggestExpertForm.list)
                    FocusButton(
                      width: 56,height: 22,
                      entity?.isFocus ?? 0,
                      type: 1,
                      radius: 16,
                      fontSize: 11,
                      expertId: entity?.expertId,
                      focusText: "+ 关注",
                      onTap: (value) {
                        entity?.isFocus = value;
                        setState(() {});
                      },
                    ).paddingOnly(top: 4)
                  ],
                ),
              ),
            ),
            if(widget.form != SuggestExpertForm.list)
            Padding(
              padding: const EdgeInsets.only(top: 8,right: 8),
              child: CheckWidget(
                value: focusList[index].contains(entity?.expertId), size: 14,
                onChanged: (value){
                    if(value){
                      focusList[index].add(entity!.expertId!);
                    }else {
                      focusList[index].remove(entity!.expertId!);
                    }
                    setState(() {});
                },
              ),
            )
          ],
        )
      ),
    );
  }

  Widget buttonArea(){
    return Row(
      children: [
        QkdButton(
          onPressed: ()=> index += 1,
          width: 106,
          height: 48,
          text: "换一组",
          backgroundColor: Colours.greyF2,
          borderRadius: 24,
          foregroundColor: Colours.grey99,
        ),
        Container(width: 12),
        Expanded(
          child: QkdButton(
            onPressed: () async{
              if(focusList.noValue || focusList[index].noValue) return;
              await UserApi.batchFocus(focusList[index]);
              widget.tapFocus?.call();
              if(widget.form == SuggestExpertForm.bottomSheet) {
                navigator?.pop();
              }
            },
            height: 48,
            width: 225,
            text: "一键关注",
            borderRadius: 24,
            foregroundColor: Colours.white,
            backgroundColor: focusList[index].hasValue?Colours.main:Colours.main1,
          ),
        )
      ],
    );
  }

  Widget head(){
    Axis direction = Axis.horizontal;
    TextStyle titleStyle = const TextStyle(fontSize: 18,fontWeight: FontWeight.w500);
    TextStyle moreStyle = const TextStyle(fontSize: 14,fontWeight: FontWeight.w500,color: Colours.grey99);
    switch(widget.form){
      case SuggestExpertForm.bottomSheet:
        direction = Axis.vertical;
        break;
      case SuggestExpertForm.list:
        direction = Axis.horizontal;
        titleStyle = const TextStyle(fontSize: 12);
        moreStyle = const TextStyle(fontSize: 12,color: Colours.grey66);
        break;
      case SuggestExpertForm.grid:
        direction = Axis.horizontal;
        titleStyle = titleStyle.copyWith(fontSize: 15);
        moreStyle = moreStyle.copyWith(fontSize: 12);
        break;
    }
    return GestureDetector(
      onTap: () => Get.toNamed(Routes.expertTop,arguments: widget.sportsId-1),
      child: Flex(
        direction: direction,
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          QkdText.style("你可能感兴趣的专家",style: titleStyle),
          if(widget.form == SuggestExpertForm.bottomSheet) Container(height: 4)
          else const Spacer(),
          Row(
            children: [
              QkdText.style("查看更多",style: moreStyle),
              Image.asset(Utils.getImgPath('arrow_right_36.png'),width: 12)
            ],
          )
        ],
      ),
    );
  }
}
